<script setup>
import {User, Lock, Message} from '@element-plus/icons-vue'
import {ref, reactive, onMounted} from 'vue'
import cryptoUtil from '@/utils/cryptoUtil.js' // 导入cryptoUtil.js

// 控制注册与登录表单的显示，默认显示注册
const isRegister = ref(false)
const rememberMe = ref(false)

const ruleForm = reactive({
  username: '',
  email: '',
  password: '',
  rePassword: ''
})

// 自定义确认密码的校验函数
const rePasswordValid = (rule, value, callback) => {
  if (value === '') {
    return callback(new Error('请再次确认密码'))
  }
  if (ruleForm.password !== value) {
    return callback(new Error('两次输入密码不一致'))
  }
  return callback()
}

// 用于注册的表单校验模型
const registerDataRules = ref({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  email: [
    {required: true, message: "请输入邮箱", trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  rePassword: [
    {validator: rePasswordValid, trigger: 'blur'}
  ]
})

import {userLoginService, creatingUserEmail} from '@/api/user.js'
import router from "@/router/index.js";
import {ElMessage} from "element-plus";
import {useTokenStore} from "@/stores/token.js";

// 登录功能
const userLoginDTO = ref({
  username: '',
  password: ''
})
const userTokenStore = useTokenStore()

// 登录按钮功能实现
const loginClick = async () => {
  userLoginDTO.value.username = ruleForm.username;
  userLoginDTO.value.password = ruleForm.password;
  const response = await userLoginService(userLoginDTO.value);

  userTokenStore.setToken(response.data);
  ElMessage.success("登录成功");
  router.push("/userBook");

  // 保存用户名和加密后的密码
  if (rememberMe.value) {
    const password = cryptoUtil.aesEncrypt(ruleForm.password, 'user'); // 使用AES加密密码
    localStorage.setItem('credentials', JSON.stringify({
      username: ruleForm.username,
      password: password
    }));
  } else {
    localStorage.removeItem('credentials');
  }
};

// 注册邮箱验证
const dialogVisible = ref(false)

const emailDTO = ref({
  username: '',
  email: '',
  password: ''
})

// 邮箱验证请求
const submitClick = async () => {
  emailDTO.value.username = ruleForm.username
  emailDTO.value.email = ruleForm.email
  emailDTO.value.password = ruleForm.password
  await creatingUserEmail(emailDTO.value)
  dialogVisible.value = false
  ElMessage.success("邮件已发送，请注意查收。如有延迟，请耐心等待片刻。")
}

// 加载保存的凭证
const loadCredentials = () => {
  const credentials = JSON.parse(localStorage.getItem('credentials'));
  if (credentials) {
    ruleForm.username = credentials.username;

    const password = cryptoUtil.aesDecrypt(credentials.password, 'user'); // 使用AES解密密码
    if (password) {
      ruleForm.password = password;
      rememberMe.value = true;
    }
  }
}

// 在组件挂载时加载凭证
onMounted(loadCredentials);
</script>


<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form ref="form" size="large" :model="ruleForm" autocomplete="off" :rules="registerDataRules"
               v-if="isRegister">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" v-model="ruleForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input :prefix-icon="Message" v-model="ruleForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" v-model="ruleForm.password" type="password"
                    placeholder="请输入密码" :show-password="true"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input :prefix-icon="Lock" v-model="ruleForm.rePassword" type="password"
                    placeholder="请输入再次密码"></el-input>
        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="dialogVisible = true">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false; clearRegisterData()">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 登录表单 -->
      <el-form ref="form" size="large" :model="ruleForm" autocomplete="off" v-else>
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" v-model="ruleForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" v-model="ruleForm.password" type="password"
                    placeholder="请输入密码" :show-password="true"></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" @click="loginClick" auto-insert-space>登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true; clearRegisterData()">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>

  <!-- 邮箱验证提示对话框 -->
  <el-dialog
      v-model="dialogVisible"
      title="邮箱验证"
      width="500"
  >
    <span>为了完成注册，请查看您的邮箱并按照收到的邮件中的详细指引进行操作。我们会发送一封包含验证链接的邮件，点击该链接即可激活您的账户。</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitClick">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>


<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: url('https://blog-majun.oss-cn-beijing.aliyuncs.com/book-long.jpg') no-repeat center / auto;
    //border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
